<template>
  <div
    class="gi-table"
    :class="{ fullscreen: isFullscreen }"
    :style="{ flex: flex ? 1 : undefined, height: height ? `${height}px` : undefined }"
    ref="giTableRef"
  >
    <a-row justify="space-between">
      <div class="w-fit eb" ref="extraRef">
        <a-space class="ebspace" ref="extraRef">
          <slot name="custom-extra"></slot>
        </a-space>
      </div>
      <template v-if="!hide">
        <template v-if="showSetting && !simple">
          <a-space :size="15">
            <slot name="custom-extra-right"></slot>
            <!-- <a-tooltip content="斑马纹">
            <a-switch v-model="stripe" size="medium" />
          </a-tooltip> -->
            <a-tooltip content="刷新">
              <a-button size="mini" class="gi_hover_btn" @click="refresh">
                <template #icon><icon-refresh :size="18" /></template>
              </a-button>
            </a-tooltip>
            <a-tooltip content="列设置" v-if="columnsSetting">
              <a-popover position="bottom" trigger="click">
                <a-button size="mini" class="gi_hover_btn">
                  <template #icon><icon-settings :size="18" /></template>
                </a-button>
                <template #content>
                  <a-table
                    row-key="title"
                    :columns="titleColumns"
                    :show-header="false"
                    :pagination="false"
                    :data="tableCache.columns"
                    :scroll="{ y: 400, x: 250 }"
                    v-model:selectedKeys="tableCache.titleSelectedKeys"
                    :row-selection="{ type: 'checkbox', showCheckedAll: true }"
                    :draggable="{ type: 'handle' }"
                    @change="handleTitleChange"
                    @select="handleTitleSelect"
                  />
                  <div class="flex flex-j-c">
                    <a-button type="primary" size="small" class="mt-10" @click="resetcolumns(true)">
                      <template #icon><icon-sync /></template>
                      <span>重置</span>
                    </a-button>
                  </div>
                </template>
              </a-popover>
            </a-tooltip>
            <a-tooltip content="全屏">
              <a-button size="mini" class="gi_hover_btn" @click="toggle">
                <template #icon>
                  <icon-fullscreen :size="18" v-if="!isFullscreen" />
                  <icon-fullscreen-exit :size="18" v-else />
                </template>
              </a-button>
            </a-tooltip>
            <!-- <a-tooltip content="显示边框">
            <a-button size="mini" class="gi_hover_btn" @click="isBordered = !isBordered">
              <template #icon>
                <icon-apps :size="18" />
              </template>
            </a-button>
          </a-tooltip> -->
            <a-radio-group type="button" size="mini" v-model="size">
              <a-radio value="mini">小</a-radio>
              <a-radio value="small">默认</a-radio>
              <a-radio value="medium">中</a-radio>
              <a-radio value="large">大</a-radio>
            </a-radio-group>
          </a-space>
        </template>
        <template v-else>
          <a-tooltip content="刷新">
            <a-button type="text" size="small" @click="refresh">
              <template #icon><icon-refresh /></template>
              刷新表格
            </a-button>
          </a-tooltip>
        </template>
      </template>
    </a-row>
    <div class="table-box m-relative" ref="tableBoxRef">
      <a-table
        v-bind="attrs"
        :columns="columns"
        :stripe="stripe"
        :size="size"
        :bordered="{ cell: isBordered }"
        ref="tableRef"
      >
        <template v-for="(item, key, i) in slots" :key="i" v-slot:[key]="{ record, rowIndex, column }">
          <slot :name="key" v-bind="{ rowIndex, record, column }"></slot>
        </template>
        <template #pagination-left>
          <slot name="foot"></slot>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { useFullscreen } from '@vueuse/core'
import { deepClone } from '@/utils/common'

defineOptions({ name: 'GiTable', inheritAttrs: false })

const router = useRouter()
const emit = defineEmits(['refresh', 'update:columns'])

const props = defineProps({
  columns: {
    default: () => [],
    type: Array,
    require: false
  },
  columnsSetting: {
    default: true,
    type: Boolean,
    require: false
  },
  id: {
    default: undefined,
    type: String,
    require: false
  },
  height: {
    default: undefined,
    type: Number,
    require: false
  },
  flex: {
    default: true,
    type: Boolean,
    require: false
  },
  simple: {
    default: false,
    type: Boolean,
    require: false
  },
  hide: {
    default: false,
    type: Boolean,
    require: false
  }
})

const attrs = useAttrs()
const slots = useSlots()
const columnsSource = ref([])
const tableCache = reactive({
  titleSelectedKeys: [],
  columns: []
})

const { fullPath } = router.currentRoute.value
let key = fullPath.replace(/[\/\\]/g, '_').split('?')[0]
if (props.id) {
  key = `${key}_${props.id}`
}

const titleColumns = reactive([
  {
    title: 'title',
    dataIndex: 'title'
  }
])

const tableRef = ref(null)
const tableBoxRef = ref(null)
const extraRef = ref(null)

const stripe = ref(true)
const size = ref('small')
const isBordered = ref(true)
const showSetting = ref(true)

const giTableRef = ref(null)
const { isFullscreen, toggle } = useFullscreen(giTableRef)

const refresh = () => {
  emit('refresh')
}

onMounted(() => {
  showSetting.value = tableBoxRef.value?.clientWidth - extraRef.value?.clientWidth >= 300
  if (!props.columnsSetting || props.simple) return
  columnsSource.value = deepClone(props.columns)
  const cacheColumns = localStorage.getItem(key)
  if (!cacheColumns) {
    resetcolumns()
  } else {
    const parseData = JSON.parse(cacheColumns)
    const columnsTemporary = []
    parseData.columns.forEach((element) => {
      const index = columnsSource.value.findIndex((item) => (item.title || '') === element)
      if (index > -1) {
        columnsTemporary.push(columnsSource.value[index])
      }
    })
    tableCache.titleSelectedKeys = parseData.titleSelectedKeys
    handleTitleChange(columnsTemporary)
  }
  window.addEventListener('resize', getWidth)
})

onUnmounted(() => {
  window.removeEventListener('resize', getWidth)
})

const getWidth = () => {
  nextTick(() => {
    if (tableBoxRef.value) {
      showSetting.value = tableBoxRef.value?.clientWidth - extraRef.value?.clientWidth >= 400
    }
  })
}

// 更新列信息
const updateColumns = () => {
  const columnsTemporary = tableCache.columns.filter((item) => {
    if (item && item.title) return tableCache.titleSelectedKeys.includes(item.title)
    return false
  })
  emit('update:columns', columnsTemporary)
  setTableCache(tableCache)
}

// 列设置表格顺序改变
const handleTitleChange = (_data) => {
  tableCache.columns = _data
  updateColumns()
}

// 列设置表格选择改变
const handleTitleSelect = (_data) => {
  tableCache.titleSelectedKeys = _data
  updateColumns()
}

const resetcolumns = (flag = false) => {
  const columnsA = []
  tableCache.titleSelectedKeys = columnsSource.value.map((item) => {
    columnsA.push(item)
    return item.title
  })
  if (flag) {
    handleTitleChange(columnsA)
  } else {
    tableCache.columns = columnsA
  }
  setTableCache(tableCache)
}

// 设置列信息缓存
const setTableCache = (value) => {
  const TableCacheColumn = value.columns.map((item) => {
    return item && item.title
  })
  localStorage.setItem(
    key,
    JSON.stringify({
      titleSelectedKeys: value.titleSelectedKeys,
      columns: TableCacheColumn
    })
  )
}

defineExpose({
  tableRef,
  resetcolumns
})
</script>

<style lang="scss" scoped>
.gi-table {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--color-bg-1);
  &.fullscreen {
    padding: $padding;
  }
  .table-box {
    flex: 1;
    margin-top: 10px;
    overflow: hidden;
  }

  :deep(.arco-table-td-content .arco-btn-text) {
    padding: 0 3px !important;
  }

  :deep(.arco-table-col-fixed-right) {
    right: -1px !important;
  }

  :deep(.arco-table-col-fixed-right .arco-table-cell) {
    padding: 5px 0 !important;
  }
}

.b--10 {
  bottom: -12px;
}
</style>
